package com.domain.service.impl;

import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.dao.*;
import com.domain.pojo.*;
import com.domain.service.LoginService;
import com.domain.utils.DateUtils;
import com.domain.utils.JwtUtils;
import com.domain.utils.NotNullUtils;
import com.domain.utils.UUIDUtils;
import com.domain.utils.wyyx.IMSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UsersWalletMapper usersWalletMapper;

    @Autowired
    private PersonalLabelMapper personalLabelMapper;

    @Autowired
    private IndustryMapper industryMapper;

    @Autowired
    private UsersSmsRecordMapper usersSmsRecordMapper;

    @Autowired
    private ContactsMapper contactsMapper;

    @Autowired
    private UsersAddFriendsMapper usersAddFriendsMapper;

    /**
     * 验证手机号是否被注册
     *
     * @param phone
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public int checkPhone(String phone) {
        int resultCount = usersMapper.selectByPhone(phone);
        return resultCount;
    }

    /**
     * 注册保存用户信息
     *
     * @param phoneNumber
     * @return
     */
    @Override
    public Map<String, Object> saveUser(String phoneNumber,
                                        String name,
                                        String gender,
                                        String birthday,
                                        String city,
                                        String industry,
                                        String personalLabel,
                                        String headImage,
                                        HttpServletRequest request) throws IOException {


        String uuid = UUIDUtils.getRandomUUID();
        String uuidtoken = UUIDUtils.getRandomUUID();
        Users users = new Users();
        users.setSpareOne(uuidtoken);
        users.setId(uuid);
        if (NotNullUtils.isNotNullObject(phoneNumber)) {
            users.setPhone(phoneNumber);
        }
        if (NotNullUtils.isNotNullObject(headImage)) {
            users.setHeadImage(headImage);
        }
        if (NotNullUtils.isNotNullObject(name)) {
            users.setName(name);
        }
        if (NotNullUtils.isNotNullObject(gender)) {
            users.setGender(new Integer(gender));
        }
        if (NotNullUtils.isNotNullObject(birthday)) {
            users.setBirthday(DateUtils.strToDate(birthday, "yyyy-MM-dd"));
        }
        if (NotNullUtils.isNotNullObject(city)) {
            users.setCity(city);
        }
        if (NotNullUtils.isNotNullObject(industry)) {
            users.setIndustry(industry);
        }
        if (NotNullUtils.isNotNullObject(personalLabel)) {
            users.setPersonalLabel(personalLabel);
        }
        users.setCreatTime(new Date());
        usersMapper.insertSelective(users);
        //生成用户钱包
        UsersWallet usersWallet = new UsersWallet();
        usersWallet.setId(UUIDUtils.getRandomUUID());
        usersWallet.setUserId(uuid);
        usersWallet.setBalance(new BigDecimal(0.00));
        usersWallet.setCreatTime(new Date());
        usersWalletMapper.insertSelective(usersWallet);
        /*注册创建im账号*/
        IMSet.createUser(uuid, name, headImage, "", "", "", uuidtoken);
        return checklogin(phoneNumber, request);
    }

    /**
     * 用户登录验证
     *
     * @param phoneNumber
     * @return
     */
    @Override
    public Map<String, Object> checklogin(String phoneNumber, HttpServletRequest request) throws UnsupportedEncodingException {
        Users user = usersMapper.selectByUserPhone(phoneNumber);
        List<UsersSmsRecord> list = usersSmsRecordMapper.selectByResgerPhoneNum(phoneNumber);
        //注册验证手机号是否有人加好友
        for (UsersSmsRecord u : list) {
            //添加加好友记录
            Users us = usersMapper.selectByUserPhone(phoneNumber);
            if (NotNullUtils.isNotNullObject(us)) {
                List<Contacts> cs = contactsMapper.selectByUsersIdAndType(us.getId());
                for (Contacts c : cs) {
                    if (!c.getSpareTwo().equals(u.getUsersId())) {
                        //添加好友记录
                        UsersAddFriends addFriends = new UsersAddFriends();
                        addFriends.setId(UUIDUtils.getRandomUUID());
                        addFriends.setFriendsId(u.getUsersId());
                        addFriends.setUsersId(us.getId());
                        addFriends.setType(Const.REQUEST_FRIENDS);
                        addFriends.setCreatTime(new Date());
                        usersAddFriendsMapper.insertSelective(addFriends);
                    }
                }
            }
        }
        Map<String, Object> maps = new HashMap<>();
        maps.put("usersId", user.getId());
        maps.put("nickname", user.getNickname());
        maps.put("name", user.getName());
        maps.put("phone", user.getPhone());
        maps.put("gender", user.getGender());
        maps.put("headImage", user.getHeadImage());
        maps.put("industry", user.getIndustry());
        maps.put("personalLabel", NotNullUtils.sliptList(user.getPersonalLabel()));
        maps.put("city", user.getCity());
        maps.put("image", NotNullUtils.sliptList(user.getImage()));
        maps.put("birthday", DateUtils.dateToStr(user.getBirthday(), "yyyy-MM-dd"));
        maps.put("spectralValue", user.getSpectralValue());
        maps.put("token", JwtUtils.sign(phoneNumber, user.getId()));
        maps.put("imToken", user.getSpareOne());
        return maps;
    }

    /**
     * 获取个人标签列表
     *
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getUserLable() {
        List<PersonalLabel> personalLabels = personalLabelMapper.selectLists();
        return Result.success("操作成功", personalLabels);
    }

    /**
     * 获取行业标签列表
     *
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getUserIndustrysList() {
        List<Industry> industries = industryMapper.selectList();
        return Result.success("操作成功", industries);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @Override
    public Result outLogin(HttpServletRequest request) {
        /* 退出登录 TODO */
        /*request.removeAttribute(Const.CURRENT_USER);*/
        return Result.success();
    }

    /**
     * 注销
     *
     * @param userId
     * @return
     */
    @Override
    public Result userCancellation(String userId) {
        //todo
        return null;
    }

    /**
     * 登陆
     *
     * @param phoneNum
     * @param password
     * @return
     */
    @Override
    public Result login(String phoneNum, String password) throws UnsupportedEncodingException {
        //验证账号是否正确
        if (!phoneNum.equals("test")) {
            return Result.success("用户名错误");
        }
        if (!password.equals("123456")) {
            return Result.success("密码错误");
        }
        Users user = usersMapper.selectByPhoneAndPassord(phoneNum, password);
        Map<String, Object> maps = new HashMap<>();
        maps.put("usersId", user.getId());
        maps.put("nickname", user.getNickname());
        maps.put("name", user.getName());
        maps.put("phone", user.getPhone());
        maps.put("gender", user.getGender());
        maps.put("headImage", user.getHeadImage());
        maps.put("industry", user.getIndustry());
        maps.put("personalLabel", NotNullUtils.sliptList(user.getPersonalLabel()));

        maps.put("city", user.getCity());
        maps.put("image", NotNullUtils.sliptList(user.getImage()));

        maps.put("spectralValue", user.getSpectralValue());
        maps.put("token", JwtUtils.sign(phoneNum, user.getId()));
        maps.put("imToken", user.getSpareOne());
        return Result.success(maps);
    }
}


